import Vue from 'vue'
import App from './App'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import VueRouter from 'vue-router'
import store from './vuex/store'
import Vuex from 'vuex'
import routes from './routes'
import 'font-awesome/css/font-awesome.min.css'
import axios from 'axios'

//配置axios的全局基本路径
axios.defaults.baseURL = 'http://localhost:8080';
//全局属性配置，在任意组件内可以使用this.$http获取axios对象
Vue.prototype.$http = axios

Vue.use(ElementUI)
Vue.use(VueRouter)
Vue.use(Vuex)

const router = new VueRouter({
  routes
})

// request拦截器
axios.interceptors.request.use(req=>{
  var token = localStorage.getItem("token");
  if(token){
    req.headers["token"] = token
  }
  return req
},error =>{
  Promise.reject(error)
})

//axios的响应拦截器
axios.interceptors.response.use(res=>{
  //判断响应内容
  if(res.data.success === false && res.data.code === 600 && res.data.message === "toLogin"){
    localStorage.removeItem("token")
    localStorage.removeItem("employeeInfo")
    localStorage.removeItem("menus")
    localStorage.removeItem("permissions")
    router.push({path: "/login"})
  }
  return res
},error => {
  Promise.reject(error)
})
//每次路由之前都要执行,每次请求都要经过路由
//每次请求都不拦截到
router.beforeEach((to, from, next) => {
  //NProgress.start();
  if (to.path == '/login' || to.path == '/register') {
    //重新登录,把原来localStorage移除掉
    localStorage.removeItem("token")
    localStorage.removeItem("employeeInfo")
    localStorage.removeItem("menus")
    localStorage.removeItem("permissions")
  }
  next();
})


//处理页面刷新动态路由失效问题
initIndexRouters();
function initIndexRouters(){
  if(!localStorage.menus){
    return;
  }
  //防止重复配置路由：4就是main.js中路由的个数 - 如果你的静态路由是6个这里要写成6
  if(router.options.routes.length>4){
    return;
  }
  let menus = localStorage.getItem('menus');
  menus = JSON.parse(menus);
  let tempRouters = [];
  menus.forEach(menu=>{
    let indexRouter = {
      path: '/',
      iconCls: menu.icon,
      name: menu.name,
      component: resolve => require(['@/views/Home'], resolve),
      children: []
    }
    if(menu.children){
      menu.children.forEach(cMenu=>{
        let cr = {
          path: cMenu.url,
          name: cMenu.name,
          component: resolve => require(['@/views/'+cMenu.component], resolve)
        }
        indexRouter.children.push(cr)
      })
    }
    tempRouters.push(indexRouter)
    router.options.routes.push(indexRouter)
  })
  //动态路由配置
  router.addRoutes(tempRouters);
}



new Vue({
  router,
  store,
  render: h => h(App) // index.html id为app的div标签下面使用<App/>和template: '<App/>',一样的效果
}).$mount('#app') // 和el: '#app'效果一样都是挂载在index.html id为app的div标签上面

